import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/layout'
import Login from '@/views/login'
import NotFound from '@/views/404'

// 导入二级路由
import Home from '@/views/layout/home'
import QA from '@/views/layout/qa'
import Video from '@/views/layout/video'
import User from '@/views/layout/user'

import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    // 重定向
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'qa',
        component: QA
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

// 全局导航守卫-->用户没有登录 不能访问/user
// 1、是否有token
// 2、有就直接放行
// 3、无就判断去哪里
// /home  /video 直接放行
// /user 拦截去登录页

const loginURL = ['/user']
router.beforeEach(function (to, from, next) {
  const token = store.state.user.token.token

  if (token) {
    // 有token
    next()
  } else {
    // 无token
    if (loginURL.some((item) => to.path === item)) {
      // next('/login')//这样写有路由故障
      router.push('/login')
    } else {
      next()
    }
  }
})

export default router

window.router = router
